package com.bjsxt.ssm.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bjsxt.ssm.Constant;
import com.bjsxt.ssm.bean.TbUser;
import com.bjsxt.ssm.service.TbUserService;
import com.bjsxt.ssm.view.Rst;

@Controller
public class LoginController {

	@Autowired
	private TbUserService tbUserService;

	@RequestMapping("/login.do")
	public String Login() {
		return "Login";
	}

	@RequestMapping("/noAuthority.do")
	public String noAuthority() {
		return "noAuthority";
	}

	
	@RequestMapping("/dologin.do")
	@ResponseBody()
	public Rst dologin(String userName, String userPwd,
			final HttpServletRequest request) {
		Rst rst = new Rst();
		if (StringUtils.isBlank(userName)) {
			rst.setCode(Constant.ERROR);
			rst.setMessage("登陆帐号不能为空");
			return rst;
		}
		if (StringUtils.isBlank(userPwd)) {
			rst.setCode(Constant.ERROR);
			rst.setMessage("登陆密码不能为空");
			return rst;
			// TODO throw Exception
		}

		List<TbUser> users = this.tbUserService.selectUserByUserName(userName,
				userPwd);
		if (!CollectionUtils.isEmpty(users)) {
			rst.setCode(Constant.SUCCESS);
			rst.setMessage("登陆成功");

			/**
			 * 潜规则 因为用户登陆帐号在系统中应该是唯一的，所以 上面根据帐号与密码查出来的用户列表的用户数量就为1，所以默认取第一个
			 * 作为存入session的用户信息
			 */
			TbUser tbUser = users.get(0);
			/** 登陆成功后把用户信息存入session **/
			HttpSession session = request.getSession();
			session.setAttribute(Constant.SESSION_KEY, tbUser);
		} else {
			rst.setCode(Constant.ERROR);
			rst.setMessage("登陆失败");
		}
		return rst;
	}
}
